package com.sdx.exception;

import com.alibaba.fastjson.JSON;
import com.ibeetl.admin.core.web.JsonResult;
import com.ibeetl.admin.core.web.JsonReturnCode;
import com.sdx.common.utils.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * @ClassName GlobalExceptionHandler
 * @Description: No Description
 * @author: tanbaocai
 * @date: 2018/5/14 16:39
 */
@ControllerAdvice
public class GlobalExceptionHandler {
	private static final Logger log = LoggerFactory.getLogger("ERRORLOG");


	@ExceptionHandler(value = LoginTimeOutException.class)
	@ResponseBody
	public ModelAndView loginTimeOutHandler(HttpServletRequest request)  {
		//打印异常信息
		ModelAndView view = new ModelAndView("/timeout.html");
		return view;
	}

	@ExceptionHandler(value = LoginTimeOutJsonException.class)
	@ResponseBody
	public JsonResult loginTimeOutJsonHandler(HttpServletRequest request, HttpServletResponse response)  {
		//打印异常信息
		JsonResult result = JsonResult.success();
		result.setCode(JsonReturnCode.TIME_OUT.getCode());
		result.setMsg(JsonReturnCode.TIME_OUT.getDesc());
		return result;
	}

	@ExceptionHandler(value = LoginFailException.class)
	@ResponseBody
	public JsonResult loginErrorHandler(HttpServletRequest request, LoginFailException e)  {
		//打印异常信息
		String errCode = printExceptionLog(request, e);
		JsonResult result = JsonResult.loginFail(e.getLoginFailExceptionCode().getCode()+"",e.getMessage());
		return result;
	}

	@ExceptionHandler(value = Exception.class)
    @ResponseBody
    public JsonResult defaultErrorHandler(HttpServletRequest request, Exception e)  {
		//打印异常信息
		String errCode = printExceptionLog(request, e);
	    JsonResult result = JsonResult.failMessage("操作失败，"+errCode+e.getMessage());
	    return result;
    }

	private String printExceptionLog(HttpServletRequest request, Exception e) {
		Map<String,String[]> params = request.getParameterMap();
		SimpleDateFormat sdf = new SimpleDateFormat("HHmm");
		String errCode = sdf.format(new Date())+ Utils.getRandomIntByLength(4);
		log.error("{}\n{}\n{}",errCode+e.getMessage(),request.getRequestURI(), JSON.toJSONString(params));
		log.error(request.getRequestURI(),e);
		e.printStackTrace();
		return errCode;
	}
}
